<?php
class UsergroupHandler
{
	public static function changeUser($iUsergroup, $iUser, $bAdmin)
	{
		try {
			// -1 = Unknown SQL error.
			// -2 = Access denied.
			// -3 = Can't change self.
			if ($_SESSION['rid'] == $iUser)
			{
				throw new MiJobException('Can\' change self');
			}

			$oCheckQuery = DataHandler::query("
				SELECT access
				FROM users_groups
				WHERE user_id = ?
				AND usergroup_id = ?
				AND access = ?
			", $_SESSION['rid'], $iUsergroup, 'admin');

			if ($oCheckQuery->rowCount() == 0)
			{
				throw new MiJobAccessException('Access denied');
			}

			DataHandler::query("
				UPDATE users_groups
				SET access = ?
				WHERE user_id = ?
				AND usergroup_id = ?
			", ($bAdmin ? 'admin' : 'user'), $iUser, $iUsergroup);

			return 1;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function delUser($iUsergroup, $iUser)
	{
		try {
			// -1 = Unknown SQL error.
			// -2 = Access denied.
			// -3 = Can't delete self.
			if ($_SESSION['rid'] == $iUser)
			{
				throw new MiJobException('Can\'t delete self');
			}

			$oCheckQuery = DataHandler::query("
				SELECT access
				FROM users_groups
				WHERE user_id = ?
				AND usergroup_id = ?
				AND access = ?
			", $_SESSION['rid'], $iUsergroup, 'admin');

			if ($oCheckQuery->rowCount() == 0)
			{
				throw new MiJobAccessException('Access denied');
			}

			DataHandler::query("
				DELETE FROM users_groups
				WHERE user_id = ?
				AND usergroup_id = ?
			", $iUser, $iUsergroup);

			return 1;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function addUser($iUsergroup, $iUser, $bAdmin)
	{
		try {
			// -1 = Unknown SQL error.
			// -2 = Access denied.
			// -3 = User already in group.
			$oCheckQuery = DataHandler::query("
				SELECT access
				FROM users_groups
				WHERE user_id = ?
				AND usergroup_id = ?
				AND access = ?
			", $_SESSION['rid'], $iUsergroup, 'admin');

			if ($oCheckQuery->rowCount() == 0)
			{
				throw new MiJobAccessException('Access denied');
			}

			$oCheckQuery = DataHandler::query("
				SELECT user_id
				FROM users_groups
				WHERE user_id = ?
				AND usergroup_id = ?
			", $iUser, $iUsergroup);

			if ($oCheckQuery->rowCount() > 0)
			{
				throw new MiJobException('User already in group');
			}

			DataHandler::query("
				INSERT INTO users_groups (
					user_id,
					usergroup_id,
					access
				) VALUES (
					?,
					?,
					?
				)
			", $iUser, $iUsergroup, ($bAdmin ? 'admin' : 'user'));

			return 1;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function addUsergroup($sName)
	{
		try {
			$oUsers = UserHandler::getUsers();
			$oAppconfig = AppconfigHandler::getConfig();
			if (!$oAppconfig['bFreeUsergroups'] && !$oUsers[$_SESSION['rid']]->bAdmin)
			{
				throw new MiJobAccessException('Access denied');
			}

			if (strlen($sName) == 0) {
				throw new MiJobException('Usergroup must have a name');
			}
			
			$oCheckQuery = DataHandler::query("
				SELECT id
				FROM usergroups
				WHERE name = ?
			", $sName);

			if ($oCheckQuery->rowCount() > 0)
			{
				throw new MiJobException('Group already exists');
			}

			DataHandler::beginTransaction();

			$oQuery = DataHandler::query("
				INSERT INTO usergroups (
					name
				) VALUES (
					?
				)
			", $sName);

			$iNewID = DataHandler::lastInsertId();

			DataHandler::query("
				INSERT INTO users_groups (
					user_id,
					usergroup_id,
					access
				) VALUES (
					?,
					?,
					?
				)
			", $_SESSION['rid'], $iNewID, 'admin');

			DataHandler::commit();

			return $iNewID;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}

	public static function changeUsergroup($iUsergroup, $sName)
	{
		try {
			$sUsers = UsergroupHandler::getUsers($iUsergroup);
			if ($sUsers[$_SESSION['rid']] != 'admin')
			{
				throw new MiJobAccessException('Access denied');
			}

			$oCheckQuery = DataHandler::query("
				SELECT id
				FROM usergroups
				WHERE name = ?
				AND id != ?
			", $sName, $iUsergroup);

			if ($oCheckQuery->rowCount() > 0)
			{
				throw new MiJobException('Group already exists');
			}

			DataHandler::query("
				UPDATE usergroups
				SET name = ?
				WHERE id = ?
			", $sName, $iUsergroup);

			return 1;
		}
		catch (Exception $e) {
			ErrorHandler::addERror($e->getMessage());
		}
	}

	public static function delUsergroup($iUsergroup)
	{
		try {
			$sUsers = UsergroupHandler::getUsers($iUsergroup);
			if ($sUsers[$_SESSION['rid']] != 'admin')
			{
				throw new MiJobAccessException('Access denied');
			}

			DataHandler::query("
				DELETE FROM usergroups
				WHERE id = ?
			", $iUsergroup);

			DataHandler::query("
				DELETE FROM users_groups
				WHERE usergroup_id = ?
			", $iUsergroup);

			return 1;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function getUsers($iUsergroup) {
		try {
			if (is_array(@$GLOBALS['usergroup']['users'][$iUsergroup]))
			{
				return $GLOBALS['usergroup']['users'][$iUsergroup];
			}

			// -1 = Unknown SQL error.
			$oQuery = DataHandler::query("
				SELECT
					user_id,
					access
				FROM users_groups
				WHERE usergroup_id = ?
			", $iUsergroup);

			$GLOBALS['usergroup']['users'][$iUsergroup] = array();
			while (list($iUser, $sAccess) = $oQuery->fetch())
			{
				$GLOBALS['usergroup']['users'][$iUsergroup][$iUser] = $sAccess;
			}
			
			return $GLOBALS['usergroup']['users'][$iUsergroup];
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function getUsergroups() {
		try {
			if (@is_array($GLOBALS['usergroups'])) {
				return $GLOBALS['usergroups'];
			}

			// -1 = Unknown SQL error.
			$oQuery = DataHandler::query("
				SELECT
					id,
					name
				FROM usergroups
				ORDER BY name
			");
			
			$oUsergroups = array();
			while (list($iID, $sName) = $oQuery->fetch(PDO::FETCH_NUM))
			{
				$oUsergroups[$iID] = new Usergroup($iID, $sName);
			}
			
			$GLOBALS['usergroups'] = $oUsergroups;
			
			return $GLOBALS['usergroups'];
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
}
?>
